package com.cn.ycy.controller;


import com.cn.ycy.dto.ReturnT;
import com.cn.ycy.dto.User;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("test")
public class TestController {

  Logger LOGGER = LoggerFactory.getLogger(TestController.class);

  @ApiOperation("get接口")
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  @ResponseBody
  public String get() {
    return "hello world";
  }

  @RequestMapping(value = "/post", method = RequestMethod.POST)
  @ResponseBody
  public ReturnT<User> post(Integer userId) {
    User user = new User();
    user.setUsername("ycy");
    user.setUserId(userId);
    return new ReturnT<User>(user);
  }

  @ApiOperation("回调")
  @RequestMapping(value = "/callback", method = RequestMethod.GET)
  @ResponseBody
  public String callBack(HttpServletRequest httpServletRequest, HttpServletResponse response) {
    LOGGER.info("httpServletRequest {},response {}", httpServletRequest, response);
    String queryString = httpServletRequest.getQueryString();
    String echostr = httpServletRequest.getParameter("echostr");
    LOGGER.info("queryString {},parameter {}", queryString, echostr);
    User user = new User();
    user.setUsername("user");
    user.setUserId(-1);

    ServletInputStream inputStream = null;
    try {
      inputStream = httpServletRequest.getInputStream();
      //获取XML数据（含加密参数）
      String postData = copyToString(inputStream, StandardCharsets.UTF_8);
      LOGGER.info("postData {}", postData);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return echostr;
  }

  public static String copyToString(InputStream in, Charset charset) throws IOException {
    StringBuilder out = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(in, charset);
    char[] buffer = new char[BUFFER_SIZE];
    int bytesRead = -1;
    while ((bytesRead = reader.read(buffer)) != -1) {
      out.append(buffer, 0, bytesRead);
    }
    return out.toString();
  }

  public static final int BUFFER_SIZE = 4096;

}
